//
//  OAuthViewController.swift
//  XinLang
//
//  Created by 张辉 on 16/5/14.
//  Copyright © 2016年 张辉. All rights reserved.
//

import UIKit
/// 登录成功通知
let CZWeiBoLoginSuccessedNotification = "CZWeiBoLoginSuccessedNotification"
class OAuthViewController: UIViewController {
  //初始化webView控件
  private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        //左侧
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(OAuthViewController.cancelButton))
        //右侧
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(OAuthViewController.autoFillButton))
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置导航栏
        title = "登录新浪微博"
        
        view.backgroundColor = UIColor.whiteColor()
       
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
        
         webView.delegate = self
        
    
    }
  //MARK:--- 监听方法
    func cancelButton(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func autoFillButton(){
    
    
        let js = "document.getElementById('userId').value='18334787338';" +
        "document.getElementById('passwd').value='Zhanghui..22';"
        
        // 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    
    }
}

// MARK: - UIWebViewDelegate
extension OAuthViewController:UIWebViewDelegate {
 
    /**
     将要开始加载请求 每次加载页面时都会调用 执行当前界面js不会被调用
     
     - parameter webView:        webview
     - parameter request:        request
     - parameter navigationType: 导航类型
     
     - returns: 是否加载 如果返回BOOL 为YES  返回NO 不正常执行
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        
        // 1 判断 request.URL 是否是回调地址
        
//        if let urlString = request.URL?.absoluteString where !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri)  {
//            
//            return true
//        }
//
     /// 如果有值就提取出该值并放在变量constantName 中并执行guard 后面的代码，如果没有值就不提取且不执行 guard 后面的代码
        guard let urlString = request.URL?.absoluteString where urlString.hasPrefix(NetworkTools.sharedTools.redirectUri) else {
            
            return true
        }
        
        
        //2.判断回调参数 如果授权成功 URL的查询字符串是否包含code
        //判断query 是否有code=
        
        guard  let query = request.URL?.query where query.hasPrefix("code=")else {
           
           print("取消授权")
           dismissViewControllerAnimated(true, completion: nil)
            
          return  false
        }
   
        print("请求字符串 " + query)
         //3.获取code请求吗
        let code = query.substringFromIndex("code=".endIndex)
        
        print("请求码 \(code)")
        
        //4.发起网络请求
      
        NetworkTools.sharedTools.loadAccessToken(code) { (result) in
            
            
            
            guard let result = result else {
                print("您的网络不给力")
                return
            }
            
            // 设置用户账户单例的数据
            UserAccount.sharUserAccount.updataUserAccount(result)
            
            //登录成功
            //1>通知代理工作
            NSNotificationCenter.defaultCenter().postNotificationName(CZWeiBoLoginSuccessedNotification, object: nil)
            
            
            
            //2>关闭视图控制器
            self.cancelButton()
        }
        
        
        return false
        
    }
    


}
